<?php

namespace App\Http\Controllers\home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use DB;

class CommentsController extends Controller
{
    //用户评论处理 $id为订单id
    public function comment($id)
    {

       $indent =  DB::table('dingdan')->where('id',$id)->first();
       $pid = $indent->pid;
       $pid = explode(',', $pid);
       $status = $indent->status;
       $status = explode(',', $status);
       $data = [];
     
        // 获取评论商品信息
       $dd = [];
       foreach ($pid as $key => $value) {
                if($status[$key] == '0'){
                    $dd[] = $pid[$key];
                }     
         } 

        foreach ($dd as $key => $value) {
                $cc[] = $value;
                                                
          $data[$key] = DB::table('goodsmain')
                       ->join('goods','goods.id' ,'=', 'goodsmain.gid')
                       ->where('goodsmain.id',$value)
                       ->select('goodsmain.pic0','goodsmain.name','goodsmain.title','goodsmain.ftitle','goods.id as goodsid','goodsmain.colour','goodsmain.price')
                       ->get();
                   }
            if(count($data) == '0'){
                
                return redirect('/wodedingdan');
            }
                
    	return view('home.comment',['dData' => $data,'indent' => $indent,'cc' => $cc ]);
    }

    public function doComment(Request $request)
    {

        //设置自定义验证信息
    	$message = [
    		   'required' => '内容不为空',
    	];

    	//设置验证规则
    	  $this->validate($request, [
    		'commentStar' => 'required',
    		'commentBody' => 'required',
    		],$message);
    	
    	// 获取提交的数据
    	$data = $request->except('_token','id','cc');
    	
     	//获取提交评论的时间
    	$data['commentPubTime'] = time();

    	// 获取用户userId
    	$data['commentUid'] = session('user')->userId;
    	// dd($data);
    	//存入用户评论数据
    	$row = DB::table('storecomment')->insertGetId($data);
        
    	if ( $row > 0 ) {

            //获取信息修改订单评价状态
            $indent=DB::table('dingdan')->where('id',$request->input('id'))->first();
            $status = explode(',', $indent->status);
            $pid = explode(',', $indent->pid);
            $cc = $request->input('cc');
              
            foreach ($status as $key => $value) {
                  if($pid[$key] == $cc){
                    $status[$key] = '1';
                  }
            }
            
            // 把状态信息转为字符串
            $status = implode(',', $status);

            DB::table('dingdan')->where('id',$request->input('id'))->update(['status'=> $status]);
    		return back()->with('msg','数据提交成功');
    	}
    	
    }
}
